package cn.yuanqiao.archive.appManager.service.impl;

import cn.yuanqiao.archive.Identify.domain.*;
import cn.yuanqiao.archive.Identify.mapper.*;
import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.*;
import cn.yuanqiao.archive.appManager.service.InitArchiveAppService;
import cn.yuanqiao.archive.bianjifabu.domain.Yqfabufangan;
import cn.yuanqiao.archive.bianjifabu.domain.YqfabufanganDa;
import cn.yuanqiao.archive.bianjifabu.domain.Yqfanganwater;
import cn.yuanqiao.archive.bianjifabu.mapper.YqfabufanganMapper;
import cn.yuanqiao.archive.chengguojieshou.domain.Yqdaarticulated;
import cn.yuanqiao.archive.chengguojieshou.domain.YqdaarticulatedLog;
import cn.yuanqiao.archive.chengguojieshou.domain.YqdaarticulatedServerLog;
import cn.yuanqiao.archive.chengguojieshou.mapper.YqdaarticulatedMapper;
import cn.yuanqiao.archive.danganzhengli.domain.HandOverDa;
import cn.yuanqiao.archive.danganzhengli.domain.HandOverReceive;
import cn.yuanqiao.archive.danganzhengli.domain.OnlinePackageDa;
import cn.yuanqiao.archive.danganzhengli.mapper.HandOverDaMapper;
import cn.yuanqiao.archive.danganzhengli.mapper.HandOverReceiveMapper;
import cn.yuanqiao.archive.danganzhengli.mapper.OnlinePackageDaMapper;
import cn.yuanqiao.archive.fondsFolder.domain.FondsFolder;
import cn.yuanqiao.archive.fondsFolder.domain.Model;
import cn.yuanqiao.archive.fondsFolder.mapper.FondsFolderMapper;
import cn.yuanqiao.archive.liyong.domain.TenantDownloadRecord;
import cn.yuanqiao.archive.liyong.mapper.TenantDownloadRecordMapper;
import cn.yuanqiao.archive.sealmanage.domain.SealManage;
import cn.yuanqiao.archive.sealmanage.mapper.SealmanageMapper;
import cn.yuanqiao.archive.storeRoom.domain.TechnicalTreatment;
import cn.yuanqiao.archive.storeRoom.mapper.TechnicalTreatmentMapper;
import cn.yuanqiao.archive.storeRoom.service.InitializationService;
import cn.yuanqiao.archive.wenjianzhengli.domain.ConveryFormat;
import cn.yuanqiao.archive.wenjianzhengli.domain.TenantTablehead;
import cn.yuanqiao.archive.wenjianzhengli.domain.Yqdatransdoc;
import cn.yuanqiao.archive.wenjianzhengli.mapper.ConveryFormatMapper;
import cn.yuanqiao.archive.wenjianzhengli.mapper.WenjianhuishouzhanMapper;
import cn.yuanqiao.archive.wenjianzhengli.mapper.YqdatransdocMapper;
import cn.yuanqiao.archive.yuguidang.domain.YuguidangArchiveForm;
import cn.yuanqiao.archive.yuguidang.mapper.yuguidangMapper;
import cn.yuanqiao.common.enums.DbIdEnum;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.SecurityUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zjj
 * @date 2023/6/15
 */
@Service
public class InitArchiveAppServiceImpl implements InitArchiveAppService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;
    @Autowired
    private TenantMdataGroupMapper mdataGroupMapper;
    @Autowired
    private TenantFieldsMapper fieldsMapper;
    @Autowired
    private TenantMdataListMapper mdataListMapper;
    @Autowired
    private TenantSysDictDataMapper dictDataMapper;
    @Autowired
    private TenantSysDictTypeMapper dictTypeMapper;
    @Autowired
    private TenantYqdaMapper yqdaMapper;
    @Autowired
    private TenantYqFolderMapper yqFolderMapper;
    @Autowired
    private TenantYqdaDocumentMapper yqdaDocumentMapper;
    @Autowired
    private TenantYqItemMapper yqItemMapper;
    @Autowired
    private TenantCodeRuleMapper codeRuleMapper;
    @Autowired
    private TenantCodeListMapper codeListMapper;
    @Autowired
    private TenantApplyMapper applyMapper;
    @Autowired
    private InitArchiveMapper initArchiveMapper;
    @Autowired
    private YqdaTreesMapper yqdaTreesMapper;
    @Autowired
    private TenantSysConfigMapper sysConfigMapper;
    @Autowired
    private IsOpenIdentifyMapper isOpenIdentifyMapper;
    @Autowired
    private BgqxIdentifyMapper bgqxIdentifyMapper;
    @Autowired
    private MiJiIdentifyMapper miJiIdentifyMapper;
    @Autowired
    private YqSyMapper yqSyMapper;
    @Autowired
    private YqTycMapper yqTycMapper;
    @Autowired
    private TenantMingancikuMapper mingancikuMapper;
    @Autowired
    private InitializationService initializationService;
    @Autowired
    private TenantCategoryServiceImpl tenantCategoryService;
    @Autowired
    private HandOverReceiveMapper handOverReceiveMapper;
    @Autowired
    private HandOverDaMapper handOverDaMapper;
    @Autowired
    private YqdaarticulatedMapper yqdaarticulatedMapper;
    @Autowired
    private YqdatransdocMapper yqdatransdocMapper;
    @Autowired
    private TenantDownloadRecordMapper downloadRecordMapper;
    @Autowired
    private DisposeMapper disposeMapper;
    @Autowired
    private DestructionMapper destructionMapper;
    @Autowired
    private FondsFolderMapper fondsFolderMapper;
    @Autowired
    private SealmanageMapper sealmanageMapper;
    @Autowired
    private yuguidangMapper yuguidangMapper;
    @Autowired
    private TenantCateMdataListMapper tenantCateMdataListMapper ;
    @Autowired
    private WenjianhuishouzhanMapper wenjianhuishouzhanMapper;
    @Autowired
    private ConveryFormatMapper converyFormatMapper;
    @Autowired
    private TenantGdfwAndBgqxMapper gdfwAndBgqxMapper;
    @Autowired
    private OnlinePackageDaMapper onlinePackageDaMapper;
    @Autowired
    private YqfabufanganMapper yqfabufanganMapper;
    @Autowired
    private TechnicalTreatmentMapper technicalTreatmentMapper;
    @Autowired
    private TenantMijiComparisonTableMapper tenantMijiComparisonTableMapper;
    @Resource
    private SqlSessionFactory sqlSessionFactory;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String initArchiveApp(JSONArray jsonArray) {
        StringBuilder msg = new StringBuilder();
        StringBuilder categoryIds = new StringBuilder();
        for(int i = 0;i<jsonArray.size();i++){
            JSONObject object = jsonArray.getJSONObject(i);
            JSONArray categoryArry = object.getJSONArray("category");
            for(int j = 0;j<categoryArry.size();j++){
                categoryIds.append(categoryArry.get(j)+",");
            }
        }
        String tenantCode = SecurityUtils.getTenantCode();

        categoryIds.deleteCharAt(categoryIds.length()-1);
        List<String> tableNames = new ArrayList<>();
        //创建基础数据表
        TenantFields fields = new TenantFields();
        tableNames.add(fields.getTableName());
        //创建元数据方案表
        TenantMdataGroup mdataGroup = new TenantMdataGroup();
        tableNames.add(mdataGroup.getTableName());
        //创建元数据明细表
        TenantMdataList mdataList = new TenantMdataList();
        tableNames.add(mdataList.getTableName());
        //创建门类表
        TenantCategory category = new TenantCategory();
        tableNames.add(category.getTableName());
        //档号定义表
        TenantCodeRule codeRule = new TenantCodeRule();
        tableNames.add(codeRule.getTableName());
        //档号明细表
        TenantCodeList codeList = new TenantCodeList();
        tableNames.add(codeList.getTableName());
        //应用定义表
        TenantApply apply = new TenantApply();
        tableNames.add(apply.getTableName());
        //创建字典表
        TenantSysDictType sysDictType = new TenantSysDictType();
        tableNames.add(sysDictType.getTableName());
        //创建字典明细表
        TenantSysDictData sysDictData = new TenantSysDictData();
        tableNames.add(sysDictData.getTableName());
        //项目总表
        TenantYqItem yqItem = new TenantYqItem();
        tableNames.add(yqItem.getTableName());
        //案卷总表
        TenantYqFolder yqFolder = new TenantYqFolder();
        tableNames.add(yqFolder.getTableName());
        //案件总表
        TenantYqda yqda = new TenantYqda();
        tableNames.add(yqda.getTableName());
        //电子文件表
        TenantYqdaDocument yqdaDocument = new TenantYqdaDocument();
        //tableNames.add(yqdaDocument.getTableName());
        //卷-件关联表
        TenantYqdaFolder yqdaFolder = new TenantYqdaFolder();
        tableNames.add(yqdaFolder.getTableName());
        //项目-卷关联表
        TenantItemFolder itemFolder = new TenantItemFolder();
        tableNames.add(itemFolder.getTableName());
        //档案树表
        YqdaTrees yqdaTrees=new YqdaTrees();
        tableNames.add(yqdaTrees.getTableName());
        //档案树-角色表
        YqdaTreesrole treesrole=new YqdaTreesrole();
        tableNames.add(treesrole.getTableName());
        //划控鉴定表 *4 +1文件附件表
        TenantYqKfjdJob yqKfjdJob=new TenantYqKfjdJob();
        tableNames.add(yqKfjdJob.getTableName());
        TenantYqKfjdTask yqKfjdTask=new TenantYqKfjdTask();
        tableNames.add(yqKfjdTask.getTableName());
        TenantYqKfjdJobDa yqKfjdJobDa=new TenantYqKfjdJobDa();
        tableNames.add(yqKfjdJobDa.getTableName());
        TenantYqKfjdFolderDa yqKfjdFolderDa=new TenantYqKfjdFolderDa();
        tableNames.add(yqKfjdFolderDa.getTableName());
        TenantYqJdFile yqJdFile=new TenantYqJdFile();
        tableNames.add(yqJdFile.getTableName());
        //敏感词库
        TenantMinganciku minganciku=new TenantMinganciku();
        tableNames.add(minganciku.getTableName());
        //保管期限鉴定表*4
        TenantYqbgqxjdJob yqbgqxjdJob=new TenantYqbgqxjdJob();
        tableNames.add(yqbgqxjdJob.getTableName());
        TenantYqbgqxjdTask yqbgqxjdTask=new TenantYqbgqxjdTask();
        tableNames.add(yqbgqxjdTask.getTableName());
        TenantYqbgqxjdJobDa yqbgqxjdJobDa=new TenantYqbgqxjdJobDa();
        tableNames.add(yqbgqxjdJobDa.getTableName());
        TenantYqbgqxjdFolderDa yqbgqxjdFolderDa=new TenantYqbgqxjdFolderDa();
        tableNames.add(yqbgqxjdFolderDa.getTableName());
        //miji鉴定表*4
        TenantYqMjjdJob yqMjjdJob=new TenantYqMjjdJob();
        tableNames.add(yqMjjdJob.getTableName());
        TenantYqMjjdTask yqMjjdTask=new TenantYqMjjdTask();
        tableNames.add(yqMjjdTask.getTableName());
        TenantYqMjjdJobDa yqMjjdJobDa=new TenantYqMjjdJobDa();
        tableNames.add(yqMjjdJobDa.getTableName());
        TenantYqMjjdFolderDa yqMjjdFolderDa=new TenantYqMjjdFolderDa();
        tableNames.add(yqMjjdFolderDa.getTableName());
        //处置表
        TenantDispose dispose=new TenantDispose();
        tableNames.add(dispose.getTableName());
        //销毁鉴定表*4
        TenantYqxhjdJob yqxhjdJob=new TenantYqxhjdJob();
        tableNames.add(yqxhjdJob.getTableName());
        TenantYqxhjdTask yqxhjdTask=new TenantYqxhjdTask();
        tableNames.add(yqxhjdTask.getTableName());
        TenantYqxhjdJobDa yqxhjdJobDa=new TenantYqxhjdJobDa();
        tableNames.add(yqxhjdJobDa.getTableName());
        TenantYqxhjdFolderDa yqxhjdFolderDa=new TenantYqxhjdFolderDa();
        tableNames.add(yqxhjdFolderDa.getTableName());
        //预归档审批表
        YuguidangArchiveForm yuguidangArchiveForm=new YuguidangArchiveForm();
        tableNames.add(yuguidangArchiveForm.getTableName());
        //创建水印表
        YqSy yqSy = new YqSy();
        tableNames.add(yqSy.getTableName());
        //创建同义词表
        YqTyc yqTyc = new YqTyc();
        tableNames.add(yqTyc.getTableName());
        //档案移交
        HandOverDa handOverDa = new HandOverDa();
        tableNames.add(handOverDa.getTableName());
        HandOverReceive receive = new HandOverReceive();
        tableNames.add(receive.getTableName());
        //电子档案接收
        OnlinePackageDa onlinePackageDa = new OnlinePackageDa();
        tableNames.add(onlinePackageDa.getTableName());
        //挂接相关表 start
        Yqdaarticulated yqdaarticulated = new Yqdaarticulated();
        tableNames.add(yqdaarticulated.getTableName());
        YqdaarticulatedLog yqdaarticulatedLog = new YqdaarticulatedLog();
        tableNames.add(yqdaarticulatedLog.getTableName());
        YqdaarticulatedServerLog yqdaarticulatedServerLog = new YqdaarticulatedServerLog();
        tableNames.add(yqdaarticulatedServerLog.getTableName());
        //挂接相关表 end

        //大事记/组织沿革相关 start
        Model model = new Model();
        tableNames.add(model.getTableName());
        FondsFolder fondsFolder = new FondsFolder();
        tableNames.add(fondsFolder.getTableName());
        //大事记/组织沿革相关 end
        //归档章管理相关 start
        SealManage sealManage = new SealManage();
        tableNames.add(sealManage.getTableName());
        //归档章管理相关 end
        //编辑发布 start
        Yqfabufangan yqfabufangan = new Yqfabufangan();
        YqfabufanganDa yqfabufanganDa = new YqfabufanganDa();
        Yqfanganwater yqfanganwater = new Yqfanganwater();
        tableNames.add(yqfabufangan.getTableName());
        tableNames.add(yqfabufanganDa.getTableName());
        tableNames.add(yqfanganwater.getTableName());
        //编辑发布 end
        Yqdatransdoc yqdatransdoc = new Yqdatransdoc();
        //定时转换ofd
        tableNames.add(yqdatransdoc.getTableName());
        //我的下载记录
        TenantDownloadRecord downloadRecord = new TenantDownloadRecord();
        tableNames.add(downloadRecord.getTableName());
        //关联字段表
        TenantRelevance tenantRelevance=new TenantRelevance();
        tableNames.add(tenantRelevance.getTableName());
        //全部检索时的表头表
        TenantTablehead tenantTablehead=new TenantTablehead();
        tableNames.add(tenantTablehead.getTableName());
        //格式表
        ConveryFormat converyFormat=new ConveryFormat();
        tableNames.add(converyFormat.getTableName());
        //三合一
        TenantGdfwAndBgqx gdfwAndBgqx=new TenantGdfwAndBgqx();
        tableNames.add(gdfwAndBgqx.getTableName());
        TenantGdfwAndBgqxRule gdfwAndBgqxRule=new TenantGdfwAndBgqxRule();
        tableNames.add(gdfwAndBgqxRule.getTableName());
        TenantMdataListShy mdataListShy=new TenantMdataListShy();
        tableNames.add(mdataListShy.getTableName());
        //库房-档案技术处理表
        TechnicalTreatment technicalTreatment = new TechnicalTreatment();
        tableNames.add(technicalTreatment.getTableName());
        tableNames.add(technicalTreatment.getTreatmentYqBoxTableName());
        //密级对照表
        TenantRyMjDzb tenantRyMjDzb=new TenantRyMjDzb();
        tenantRyMjDzb.setTableName(tenantCode+TenantRyMjDzb.BIGTABLENAME);
        tableNames.add(tenantRyMjDzb.getTableName());
        try {
            //库房-档案技术处理表
            technicalTreatmentMapper.createTable(technicalTreatment.getTableName());
            technicalTreatmentMapper.createTableTreatmentYqBox(technicalTreatment.getTreatmentYqBoxTableName());
            //创建基础数据表
            fieldsMapper.createFieldsTable(fields.getTableName());
            fieldsMapper.initFields(fields.getTableName());
            //创建元数据方案表
            mdataGroupMapper.careateMdataGroupTable(mdataGroup.getTableName());
            //创建门类表
            tenantCategoryMapper.createCategoryTable(category.getTableName());
            //创建元数据明细表
            mdataListMapper.careateMdataListTable(mdataList.getTableName());
            //档号定义表
            codeRuleMapper.createCodeRuleTable(codeRule.getTableName());
            //档号明细表
            codeListMapper.createCodeListTable(codeList.getTableName());
            //应用定义表
            applyMapper.createApplyTable(apply.getTableName());
            //档案树表
            yqdaTreesMapper.createTreeTable(yqdaTrees.getTableName());
            //档案树-角色表
            yqdaTreesMapper.createTreeroleTable(treesrole.getTableName());
            //划控鉴定表 *4
            isOpenIdentifyMapper.createKfjdJobTable(yqKfjdJob.getTableName());//任务表
            isOpenIdentifyMapper.createKfjdTask(yqKfjdTask.getTableName());//流程表
            isOpenIdentifyMapper.createKfjdJobDaTable(yqKfjdJobDa.getTableName());//档案表
            isOpenIdentifyMapper.createKfjdFolderDaTable(yqKfjdFolderDa.getTableName());//卷件关联表
            //鉴定上传文件表 *1
            isOpenIdentifyMapper.createJdFileTable(yqJdFile.getTableName());
            //保管期限鉴定表*4
            bgqxIdentifyMapper.createbgqxjdJobTable(yqbgqxjdJob.getTableName());
            bgqxIdentifyMapper.createbgqxjdTask(yqbgqxjdTask.getTableName());
            bgqxIdentifyMapper.createbgqxjdJobDaTable(yqbgqxjdJobDa.getTableName());
            bgqxIdentifyMapper.createbgqxjdFolderDaTable(yqbgqxjdFolderDa.getTableName());
            //敏感词库表
            mingancikuMapper.createminganciTable(minganciku.getTableName());
            //处置表
            disposeMapper.createTable(dispose.getTableName());
            //销毁表*4
            destructionMapper.createdestructionJobTable(yqxhjdJob.getTableName());
            destructionMapper.createdestructionJobDaTable(yqxhjdJobDa.getTableName());
            destructionMapper.createdestructionjdFolderDaTable(yqxhjdFolderDa.getTableName());
            destructionMapper.createdestructionjdTask(yqxhjdTask.getTableName());
            //miji鉴定表*4
            miJiIdentifyMapper.createMjjdJobTable(yqMjjdJob.getTableName());
            miJiIdentifyMapper.createMjjdJobDaTable(yqMjjdJobDa.getTableName());
            miJiIdentifyMapper.createMjjdFolderDaTable(yqMjjdFolderDa.getTableName());
            miJiIdentifyMapper.createMjjdTask(yqMjjdTask.getTableName());
            //预归档表
            yuguidangMapper.createTable(yuguidangArchiveForm.getTableName());
            //创建水印表
            yqSyMapper.createYqSyTable(yqSy.getTableName());
            yqSyMapper.initYqSy(yqSy.getTableName());
            //创建同义词表
            yqTycMapper.createYqTycTable(yqTyc.getTableName());
            yqTycMapper.initYqTyc(yqTyc.getTableName());
            //档案移交
            handOverReceiveMapper.createTableHandOverReceive(receive.getTableName());
            handOverDaMapper.createHandOverDaMapper(handOverDa.getTableName());
            //电子档案接收
            onlinePackageDaMapper.createOnlinePackageDa(onlinePackageDa.getTableName());
            //挂接相关表 start
            yqdaarticulatedMapper.createArticulated(yqdaarticulated.getTableName());
            yqdaarticulatedMapper.createArticulatedLog(yqdaarticulatedLog.getTableName());
            yqdaarticulatedMapper.createArticulatedServerLog(yqdaarticulatedServerLog.getTableName());
            //挂接相关表 end

            //大事记/组织沿革相关 start
            fondsFolderMapper.createFondsFolder(fondsFolder.getTableName());
            fondsFolderMapper.createModelManage(model.getTableName());
            //大事记/组织沿革相关 end

            //归档章管理相关 start
            sealmanageMapper.createSealManage(sealManage.getTableName());
            //归档章管理相关 end

            //编辑发布 start
            yqfabufanganMapper.createFabufangan(yqfabufangan.getTableName());
            yqfabufanganMapper.createFabufanganDa(yqfabufanganDa.getTableName());
            yqfabufanganMapper.createFanganWater(yqfanganwater.getTableName());
            //编辑发布 end

            //定时转换ofd
            yqdatransdocMapper.createYqdatransdoc(yqdatransdoc.getTableName());
            //我的下载记录
            downloadRecordMapper.createDownloadRecord(downloadRecord.getTableName());
            //关联字段表
            tenantCateMdataListMapper.createReleTable(tenantRelevance.getTableName());
            wenjianhuishouzhanMapper.createHeadTable(tenantTablehead.getTableName());
            //格式表 xy
            converyFormatMapper.createFormatTable(converyFormat.getTableName());
            //三合一
            gdfwAndBgqxMapper.creatTabelgdfwandbgqx(gdfwAndBgqx.getTableName());
            gdfwAndBgqxMapper.creatTabelgdfwandbgqxRule(gdfwAndBgqxRule.getTableName());
            gdfwAndBgqxMapper.creatTabelmdatalistshy(mdataListShy.getTableName());
            //密级对照表
            tenantMijiComparisonTableMapper.createtable(tenantRyMjDzb.getTableName());
            //查询基础数据公用字段
            fields.setIsCommon("1");
            List<TenantFields> fieldsList = fieldsMapper.selectTenantFieldsList(fields);
            List<TenantMdataList> mdataListsCommon = new ArrayList<>();
            for(TenantFields fieldsData:fieldsList){
                TenantMdataList list = new TenantMdataList();
                list.setType(Integer.valueOf(fieldsData.getType()));
                list.setFieldType(Integer.valueOf(fieldsData.getFieldType()));
                list.setFieldName(fieldsData.getFieldName());
                list.setDataLength(Integer.valueOf(fieldsData.getFieldLength()));
                mdataListsCommon.add(list);
            }

            for(int i = 0;i<jsonArray.size();i++){
                JSONObject object = jsonArray.getJSONObject(i);
                JSONArray categoryArry = object.getJSONArray("category"); //获取门类id
                for(int j = 0;j<categoryArry.size();j++){
                    TenantCategory category1 = tenantCategoryMapper.categoryModelList(categoryArry.getLong(j));//查询门类模板
                    Long categoryId = category1.getId();//模板id
                    //添加元数据方案
                    TenantMdataGroup mdataGroup1 = mdataGroupMapper.getMdataGroupModel(categoryId); //查询模板
                    Long groupId = mdataGroup1.getId(); //模板id
                    mdataGroupMapper.insertTenantMdataGroup(mdataGroup1);
                    //添加元数据方案明细
                    List<TenantMdataList> mdataLists = mdataListMapper.getMdataListModel(groupId);
                    for(TenantMdataList mdata:mdataLists){
                        mdata.setGroupId(mdataGroup1.getId());
                        mdataListMapper.insertTenantMdataList(mdata);
                    }
                    //添加门类
                    category1.setFondsCode(object.getString("fondsCode")); //全宗号
                    category1.setGroupId(mdataGroup1.getId());  //元数据方案ID
                    tenantCategoryMapper.insertTenantCategory(category1);

                    //档号定义表
                    List<TenantCodeRule> codeRuleList = codeRuleMapper.getCodeRuleModel(categoryId);
                    for(TenantCodeRule codeRule1:codeRuleList){
                        Long codeRuleId = codeRule1.getId();
                        codeRule1.setCategoryModelId(category1.getId()); //新门类id
                        codeRuleMapper.insertTenantCodeRule(codeRule1);
                        //档号明细
                        List<TenantCodeList> codeListList = codeListMapper.getCodeListModel(codeRuleId);
                        for(TenantCodeList codeList1:codeListList){
                            codeList1.setArchivalcodeRuleId(codeRule1.getId());
                            codeListMapper.insertTenantCodeList(codeList1);
                        }
                    }

                    //应用定义表
                    List<TenantApply> applyList = applyMapper.getApplyModel(categoryId);
                    for(TenantApply apply1:applyList){
                        apply1.setCategoryId(category1.getId());
                        applyMapper.insertTenantApply(apply1);
                    }
                    //三合一 1
                    List<TenantMdataListShy> mdataShyList=mdataListMapper.mdataShyList(categoryId);
                    for(TenantMdataListShy shy:mdataShyList){
                        shy.setId(SnowflakeIdGenerator.generateId());
                        shy.setCategoryId(category1.getId());
                        shy.setGroupId(category1.getGroupId());
                        mdataListMapper.addmdatatoshy(shy);
                    }
                    //此处更新shy表的mdataid
                    gdfwAndBgqxMapper.updatemdataid(mdataListShy.getTableName(),mdataList.getTableName());
                    //三合一 2
                    List<TenantGdfwAndBgqx> gdfwAndBgqxList=gdfwAndBgqxMapper.getgdfwandbgqx(categoryId);
                    for(TenantGdfwAndBgqx gdfwAndBgqx1:gdfwAndBgqxList){
                        Long nowid=SnowflakeIdGenerator.generateId();
                        List<TenantGdfwAndBgqxRule> gdfwAndBgqxRuleList=gdfwAndBgqxMapper.getgdfwandbgqxrule(gdfwAndBgqx1.getId());
                        for(TenantGdfwAndBgqxRule gdfwAndBgqxRule1:gdfwAndBgqxRuleList){
                            gdfwAndBgqxRule1.setId(SnowflakeIdGenerator.generateId());
                            gdfwAndBgqxRule1.setZdId(nowid);
                            gdfwAndBgqxMapper.addtj(gdfwAndBgqxRule1);
                        }
                        gdfwAndBgqx1.setId(nowid);
                        gdfwAndBgqx1.setCategoryId(category1.getId());
                        gdfwAndBgqxMapper.addzd(gdfwAndBgqx1);

                    }
                    //三合一 3

                    //关联字段
                    List<TenantRelevance> relevanceList= tenantCateMdataListMapper.getmodelrele(groupId);
                    for (int k = 0; k < relevanceList.size(); k++) {
                        TenantRelevance relevance=new TenantRelevance();
                        relevance.setGroupId(groupId);
                        relevance.setFieldName(relevanceList.get(k).getFieldName());
                        relevance.setFieldType(relevanceList.get(k).getFieldType());
                        relevance.setReleField(relevanceList.get(k).getReleField());
                        relevance.setRelefieldType(relevanceList.get(k).getRelefieldType());
                        relevance.setRelefieldLevel(relevanceList.get(k).getRelefieldLevel());
                        relevance.setRelation(relevanceList.get(k).getRelation());
                        tenantCateMdataListMapper.addrelevance(relevance);
                    }
                    //密级对照表
                    List<TenantRyMjDzb> remjdzblist=tenantMijiComparisonTableMapper.getYqdaMijiComparsionTable();
                    for (int k = 0; k < remjdzblist.size(); k++) {
                        TenantRyMjDzb remidzb=new TenantRyMjDzb();
                        remidzb.setTableName(tenantCode+TenantRyMjDzb.BIGTABLENAME);
                        remidzb.setDaMj(remjdzblist.get(k).getDaMj());
                        remidzb.setRyMj(remjdzblist.get(k).getRyMj());
                        tenantMijiComparisonTableMapper.add(remidzb,remidzb.getTableName());
                    }
                }
            }
            //修改应用定义表menuid
            applyMapper.updatemenuId(new TenantApply().getTableName(),tenantCode);
            //创建字典表
            dictTypeMapper.careateDictTypeTable(sysDictType.getTableName());
            dictTypeMapper.initDictType(sysDictType.getTableName());
            //创建字典明细表
            dictDataMapper.careateDictDataTable(sysDictData.getTableName());
            dictDataMapper.initDictData(sysDictData.getTableName());
            //创建系统参数配置表
            List<TenantSysConfig> configList = sysConfigMapper.selectSysConfigMode();
            sysConfigMapper.deleteConfigByIdTeantCode(tenantCode);
            for(TenantSysConfig config:configList){
                config.setTenantCode(tenantCode);
                sysConfigMapper.insertConfig(config);
            }

            //卷-件关联表
            initArchiveMapper.createYqdaFolder(yqdaFolder.getTableName());
            //项目-卷关联表
            initArchiveMapper.createItemFolder(itemFolder.getTableName());
            //业务行为表
            initArchiveMapper.createBusinessActivity(tenantCode.toUpperCase());
            tableNames.add(tenantCode.toUpperCase()+"_BUSINESSACTIVITY");
            //查询所有业务字段
            Map<String,String> xmSet = new HashMap<>();
            Map<String,String> juanSet = new HashMap<>();
            Map<String,String> jianSet = new HashMap<>();
            List<TenantMdataList> mdataLists = mdataListMapper.selectTenantMdataListList(new TenantMdataList());
            //基础数据的公用字段
            mdataLists.addAll(mdataListsCommon);
            for(TenantMdataList data:mdataLists){
                if(data.getType() == 0){
                    jianSet.put(data.getFieldName(),colType(jianSet,data.getFieldName(),data.getFieldType(),data.getDataLength()));
                }else if(data.getType() == 1){
                    juanSet.put(data.getFieldName(),colType(juanSet,data.getFieldName(),data.getFieldType(),data.getDataLength()));
                }else if(data.getType() == 3){
                    xmSet.put(data.getFieldName(),colType(xmSet,data.getFieldName(),data.getFieldType(),data.getDataLength()));
                }
            }

            //项目总表
            yqItem.setColNames(xmSet);
            yqItemMapper.createYqItemTable(yqItem);
            //卷总表
            yqFolder.setColNames(juanSet);
            yqFolderMapper.createYqFolderTable(yqFolder);
            //件总表
            yqda.setColNames(jianSet);
            yqdaMapper.createYqdaTable(yqda);

            //业务分表
            List<TenantCategory> categoryList = tenantCategoryMapper.selectTenantCategoryList(new TenantCategory());
            for(TenantCategory category1:categoryList){
                TenantMdataList select = new TenantMdataList();
                select.setGroupId(category1.getGroupId());
                List<TenantMdataList> tenantMdataLists = mdataListMapper.selectTenantMdataListList(select);
                //租户代码_全宗号_门类代码_上架方式_卷/件
                Map<String,String> xmDisperseCol = new HashMap<>();
                Map<String,String> juanDisperseCol = new HashMap<>();
                Map<String,String> jianDisperseCol = new HashMap<>();
                Map<String,String> efileDisperseCol = new HashMap<>();

                for(TenantMdataList data:tenantMdataLists){
                    if(data.getType() == 3){
                        xmDisperseCol.put(data.getFieldName(),colType(xmDisperseCol,data.getFieldName(),data.getFieldType(),data.getDataLength()));
                    }else if(data.getType() == 1){
                        juanDisperseCol.put(data.getFieldName(),colType(juanDisperseCol,data.getFieldName(),data.getFieldType(),data.getDataLength()));
                    }else if(data.getType() == 0){
                        jianDisperseCol.put(data.getFieldName(),colType(jianDisperseCol,data.getFieldName(),data.getFieldType(),data.getDataLength()));
                    }else if(data.getType() == 2){
                        efileDisperseCol.put(data.getFieldName(),colType(efileDisperseCol,data.getFieldName(),data.getFieldType(),data.getDataLength()));
                    }
                }
                TenantCategory tenantCategory = new TenantCategory();
                String disperseTabel = tenantCode+"_"+category1.getFondsCode()+"_"+category1.getCode()+"_"+category1.getType();
                if(category1.getType() == 3){
                    //创建项目表
                    String disperseTabelName = getDisperseTabel(disperseTabel+"_X");
                    initArchiveMapper.createDisperseTabe(disperseTabelName,xmDisperseCol);
                    tenantCategory.setItemTableName(disperseTabelName);
                    tableNames.add(disperseTabelName);
                }
                if(category1.getType() == 3 || category1.getType() == 1){
                    //创建卷表
                    String disperseTabelName = getDisperseTabel(disperseTabel+"_V");
                    initArchiveMapper.createDisperseTabe(disperseTabelName,juanDisperseCol);
                    tenantCategory.setFolderTableName(disperseTabelName);
                    tableNames.add(disperseTabelName);
                }
                //创建件表
                String disperseTabelName = getDisperseTabel(disperseTabel+"_F");
                initArchiveMapper.createDisperseTabe(disperseTabelName,jianDisperseCol);
                tenantCategory.setFileTableName(disperseTabelName);
                tableNames.add(disperseTabelName);
                //创建电子文件表
                String EdisperseTabelName = getDisperseTabel(disperseTabel+"_E");
                yqdaDocument.setColNames(efileDisperseCol);
                yqdaDocument.setTableName(EdisperseTabelName);
                yqdaDocumentMapper.createYqdaDocumentTable(yqdaDocument);
                tenantCategory.setEfileTableName(EdisperseTabelName);
                tableNames.add(EdisperseTabelName);

                tenantCategory.setId(category1.getId());
                tenantCategoryMapper.updateTenantCategory(tenantCategory);

                //判断是检察类的表则添加检察类相关的表
                String storeType = category1.getStoreType();
                logger.info("检察类相关的表添加start；author：syd");
                tenantCategoryService.addJcTable(tenantCode,storeType);
                logger.info("检察类相关的表添加end；author：syd");


            }
            //赵常飞
            initializationService.insertYqtable("YUGD_FORM","预归档表单表","预归档表单表",1);
            //其他表初始化  xy
            initializationService.initializationTable();
        }catch (Exception e){
            //回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            msg.append("创建失败错误信息："+e.getMessage()+";"+e.toString());
            logger.error(e.getMessage(),e);
            //创建失败 手动删除表
            //1.验证业务主表是否有数据，如果有则不删除
            //卷总表
            int juan = initArchiveMapper.isExistTable(yqFolder.getTableName());
            if(juan>0){
                int num = initArchiveMapper.countTable(yqFolder.getTableName());
                if(num >0){
                    return msg.append(";回滚中发现卷总表存在数据，回滚失败！").toString();
                }
            }

            //项目总表
            int xm = initArchiveMapper.isExistTable(yqItem.getTableName());
            if(xm>0){
                int num = initArchiveMapper.countTable(yqItem.getTableName());
                if(num >0){
                    return msg.append(";回滚中发现项目总表存在数据，回滚失败！").toString();
                }
            }

            //件总表
            int jian = initArchiveMapper.isExistTable(yqda.getTableName());
            if(jian>0){
                int num = initArchiveMapper.countTable(yqda.getTableName());
                if(num >0){
                    return msg.append(";回滚中发现件总表存在数据，回滚失败！").toString();
                }
            }

            //删除表
            dropTable(tableNames);
            msg.append(";创建表数据已回滚！");
        }

        return msg.toString();
        //添加门类数据
        /*for(int i = 0;i<jsonArray.size();i++){
            JSONObject object = jsonArray.getJSONObject(i);
        }*/
    }

    //表名后缀
    private static String [] suffix = new String []{"A","B","C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    private String getDisperseTabel(String initTable){
        String tableName = "";
        //防止表名重复表名后加字母
        for(int i =0;i<26;i++){
            String tableSuffix = (initTable+"_"+suffix[i]).toUpperCase();
            int num = initArchiveMapper.isExistTable(tableSuffix);
            if(num == 0){
                tableName = tableSuffix;
                break;
            }
        }
        return tableName;
    }

    private void dropTable(List<String> tableList){
        for(String tableName:tableList){
            int table = initArchiveMapper.isExistTable(tableName);
            if(table>0){
                initArchiveMapper.dropTable(tableName);
            }
        }
    }

    private String colType(Map<String,String> data,String colName,Integer fieldType,Integer dataLength){
        //1：整型 2：字符型 3：日期 4：浮点 5：文本 6：图像 7:长整型
        if(data.get(colName) != null && fieldType == 2){
            //如果字段已存 则已长度最大的为准
            logger.info(data.get(colName)+"---------"+colName+"--------------"+fieldType+"------------"+dataLength);
            Integer len = Integer.valueOf(data.get(colName).substring(data.get(colName).indexOf("(")+1,data.get(colName).indexOf(")")));
            if((dataLength*2)<len){
                return data.get(colName);
            }
        }
        String col ="";
        String databaseId = sqlSessionFactory.getConfiguration().getDatabaseId();
        if(fieldType == 1){
            if(databaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode())){
                col = " BIGINT";
            }else {
                col = " INT";
            }
        }else if(fieldType == 3){
            col = " VARCHAR(50)";
        }else if(fieldType == 4){
            col = " DOUBLE";
        }else if(fieldType == 5){
            col = " TEXT";
        }else if(fieldType == 7){
            col = " BIGINT";
        }else {
            col = " VARCHAR("+(dataLength*2)+")";
        }
        return colName+col;
    }
}
